<script setup>
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'
import {ref} from 'vue'

const books = ref('')
//声明一个异步的函数
import {
  bookListService,
  bookAddService,
  bookUpdateService,
  bookDeleteService
} from '@/api/book.js'


//分页条数据模型
const pageNum = ref(1)  // 默认第1页
const total = ref(0)    // 默认总条数0
const pageSize = ref(10) // 默认每页10条

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  // console.log(pageSize.value)
  bookList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  bookList()
}

const bookList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }
  let result = await bookListService(params);

  // console.log(result.data.records)
  books.value = result.data.records;
  // console.log(books.value)
  pageNum.value = result.data.current;
  total.value = result.data.total;
  pageSize.value = result.data.size;

}
bookList();
//控制添加图书弹窗
const dialogVisible = ref(false)

//添加图书数据模型
const bookModel = ref({
  bookId: '',
  bookName: '',
  isbn: '',
  press: '',
  author: '',
  price: '',
  status: '',
})
//添加图书表单校验
const rules = {
  bookId: [
    {required: true, message: '请输入图书编号', trigger: 'blur'},
  ],
  bookName: [
    {required: true, message: '请输入图书名称', trigger: 'blur'},
  ],
  isbn: [
    {required: true, message: '请输入图书标准ISBN编号', trigger: 'blur'},
  ],
  press: [
    {required: true, message: '请输入图书出版社', trigger: 'blur'},
  ],
  author: [
    {required: true, message: '请输入图书作者', trigger: 'blur'},
  ],
  price: [
    {required: true, message: '请输入图书价格', trigger: 'blur'},
  ],
  status: [
    {required: true, message: '请选择图书状态', trigger: 'blur'},
  ]
}


//调用接口,添加表单
import {ElMessage} from 'element-plus'

const addBook = async () => {
  console.log(bookModel.value)
  //调用接口
  let result = await bookAddService(bookModel.value);
  ElMessage.success(result.msg ? result.msg : '添加成功')

  //调用获取所有图书图书分类的函数
  await bookList();
  clearData();
  console.log(bookModel.value)
  dialogVisible.value = false;
}

//定义变量,控制标题的展示
const title = ref('')

//展示编辑弹窗
const showDialog = (row) => {
  dialogVisible.value = true;
  title.value = '编辑图书分类'
  //数据拷贝
  bookModel.value.bookName = row.bookName;
  bookModel.value.bookPress = row.bookPress;
  bookModel.value.isbn = row.isbn;
  bookModel.value.author = row.author;
  bookModel.value.press = row.press;
  bookModel.value.price = row.price;
  //扩展bookId属性,将来需要传递给后台,完成图书分类的修改
  bookModel.value.bookId = row.bookId
}

//编辑图书分类
const updateBook = async () => {
  console.log(bookModel.value);

  const bookId = bookModel.value.bookId;
  console.log(bookId)
  // 调用接口
  let result = await bookUpdateService(bookId, bookModel.value);

  // 显示成功消息
  ElMessage.success(result.msg ? result.msg : '修改成功');

  // 调用获取所有图书列表的函数（假设 bookList 是获取图书列表的函数）
  await bookList();

  clearData();
  console.log(bookModel.value)

  // 隐藏弹窗
  dialogVisible.value = false;
};

//清空模型的数据
const clearData = () => {
  bookModel.value.bookName = '';
  bookModel.value.press = '';
  bookModel.value.bookId = '';
  bookModel.value.isbn = '';
  bookModel.value.author = '';
  bookModel.value.price = '';
  bookModel.value.status = '';
}

//删除图书分类
import {ElMessageBox} from 'element-plus'

const deleteBook = (row) => {
  //提示用户  确认框

  ElMessageBox.confirm(
      '你确认要删除该图书信息吗?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        //调用接口
        let result = await bookDeleteService(row.bookId);
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        //刷新列表
        bookList();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '用户取消了删除',
        })
      })
}
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>图书总览</span>
        <div class="extra">
          <el-button type="primary" @click="dialogVisible = true; title = '添加图书'; clearData()">添加图书</el-button>
        </div>
      </div>
    </template>
    <el-table :data="books" style="wbookIdth: 100%">
      <el-table-column label="图书编号" prop="bookId"></el-table-column>
      <el-table-column label="图书名称" prop="bookName"></el-table-column>
      <el-table-column label="图书标准ISBN编号" prop="isbn"></el-table-column>
      <el-table-column label="图书出版社" prop="press"></el-table-column>
      <el-table-column label="图书作者" prop="author"></el-table-column>
      <el-table-column label="图书价格" prop="price"></el-table-column>
      <el-table-column label="图书状态" wbookIdth="100">
        <template #default="{ row }">
          <el-tag v-if="row.statusDesc == '可借阅'" type="success">可借阅</el-tag>
          <el-tag v-else type="danger">已借出</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" wbookIdth="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteBook(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>

    <!-- 添加图书弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" wbookIdth="30%">
      <el-form :model="bookModel" :rules="rules" label-wbookIdth="100px" style="padding-right: 30px">
        <el-form-item label="图书名称" prop="bookName">
          <el-input v-model="bookModel.bookName" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="图书标准ISBN编号" prop="bookIsbn">
          <el-input v-model="bookModel.isbn" minlength="1" maxlength="15"></el-input>
        </el-form-item>
        <el-form-item label="图书出版社" prop="bookPress">
          <el-input v-model="bookModel.press" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="图书作者" prop="bookAuthor">
          <el-input v-model="bookModel.author" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="图书价格" prop="bookPrice">
          <el-input v-model="bookModel.price" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="图书状态" prop="bookStatus">
          <el-select v-model="bookModel.status" placeholder="请选择图书状态">
            <el-option label="可借阅" value="可借阅"></el-option>
            <el-option label="已借出" value="已借出"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary"
                               @click="title == '添加图书' ? addBook() : updateBook()"> 确认 </el-button>
                </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>